package com.student.wym.controller;

import com.student.wym.po.Exam;
import com.student.wym.po.Student;
import com.student.wym.service.IExamService;
import com.student.wym.service.IStudentService;
import com.student.wym.util.JSONResult;
import com.student.wym.util.PageList;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @Autowired
    private IExamService examService;

    @RequestMapping(value = "/goPage", method = RequestMethod.GET)
    public String goPage() {
        return "list_student";
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public PageList list(HttpServletRequest request) {
        /**
         * 直接用所用学生作为考试学生，不考虑exam_id
         */
        List<Student> students = studentService.findAll();
        PageList resultList = new PageList();
        resultList.setRows(students);
        resultList.setTotal(students.size());
        return resultList;
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult upload(@RequestParam("file") MultipartFile file) { //为了方便，就不用vo了  0.0
        Exam currentExam = examService.findCurrentExam();
        if (currentExam == null) {
            return new JSONResult(1, "请新建考试再导入学生");
        }
        if (file.getSize() == 0) {
            return new JSONResult(1, "导入前请先选择文件");
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if (!suffix.equals(".xlsx") && !suffix.equals(".xls")) {
            return new JSONResult(1, "只能导入excel文件");
        }
        //1....List<Student> students = new ArrayList<Student>();
        try {
            Workbook wb = null;
            if (suffix.equals(".xlsx")) { //2007
                wb = new XSSFWorkbook(file.getInputStream());
            } else  //2003
                wb = new HSSFWorkbook(file.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i); //读取表中的行
                Student student = new Student();
                student.setExamId(currentExam.getId());//当前考试id
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                student.setIdx(Integer.parseInt(row.getCell(0).getStringCellValue()));
                row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);//防止出现纯数字错误
                student.setGrade(row.getCell(1).getStringCellValue());//年级
                student.setDepartment(row.getCell(2).getStringCellValue());//学院
                student.setMajor(row.getCell(3).getStringCellValue());//专业
                student.setName(row.getCell(4).getStringCellValue());//姓名
                row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                student.setStudentNo(row.getCell(5).getStringCellValue());//学号
                student.setSchoolNo(row.getCell(6).getStringCellValue());//党校号
                student.setExamState(0);//初试状态，未开考
                student.setExamScore(0);
                student.setMakeUpState(0);//补考状态，未开考
                student.setMakeUpScore(0);
                student.setState(0);
                student.setExamTime(currentExam.getExamTime());
                student.setMakeUpTime(currentExam.getExamTime());
                student.setPass(currentExam.getPass());
                student.setAgaine(currentExam.getAgaine());
                student.setExamName(currentExam.getExamName());
                //2...students.add(student);
                studentService.insert(student);
            }
            // 3...studentService.insertAll(students);
            return new JSONResult(0, "导入学生成功");
        } catch (IOException e) {
            System.out.println(e.getMessage());//logger.debug
            return new JSONResult(1, "导入出现错误");
        }
    }

    @RequestMapping("/downLoad")
    @ResponseBody
    public JSONResult downLoad(HttpServletRequest request, HttpServletResponse response) {
        List<Student> students = studentService.findAll();
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            if (students != null && students.size() != 0) {
                int len = students.size();
                Sheet sheet = workbook.createSheet();
                //第一行
                Row row = sheet.createRow(0);
                Cell cell = row.createCell(0, Cell.CELL_TYPE_STRING);
                cell.setCellValue("编号");
                cell = row.createCell(1, Cell.CELL_TYPE_STRING);
                cell.setCellValue("年级");
                cell = row.createCell(2, Cell.CELL_TYPE_STRING);
                cell.setCellValue("学院");
                cell = row.createCell(3, Cell.CELL_TYPE_STRING);
                cell.setCellValue("专业");
                cell = row.createCell(4, Cell.CELL_TYPE_STRING);
                cell.setCellValue("姓名");
                cell = row.createCell(5, Cell.CELL_TYPE_STRING);
                cell.setCellValue("学号");
                cell = row.createCell(6, Cell.CELL_TYPE_STRING);
                cell.setCellValue("党校号");
                cell = row.createCell(7, Cell.CELL_TYPE_STRING);
                cell.setCellValue("初考成绩");
                cell = row.createCell(8, Cell.CELL_TYPE_STRING);
                cell.setCellValue("补考成绩");
                //后面行
                for (int i = 0; i < len; i++) {
                    row = sheet.createRow(i + 1);
                    cell = row.createCell(0, Cell.CELL_TYPE_STRING);
                    cell.setCellValue(students.get(i).getIdx());
                    cell = row.createCell(1, Cell.CELL_TYPE_STRING);
                    cell.setCellValue(students.get(i).getGrade());  //年级
                    cell = row.createCell(2, Cell.CELL_TYPE_STRING);
                    cell.setCellValue(students.get(i).getDepartment());  //学院
                    cell = row.createCell(3, Cell.CELL_TYPE_STRING);
                    cell.setCellValue(students.get(i).getMajor()); //专业
                    cell = row.createCell(4, Cell.CELL_TYPE_STRING);
                    cell.setCellValue(students.get(i).getName()); //姓名
                    cell = row.createCell(5, Cell.CELL_TYPE_STRING);
                    cell.setCellValue(students.get(i).getStudentNo() + ""); //学号
                    cell = row.createCell(6, Cell.CELL_TYPE_STRING);
                    cell.setCellValue(students.get(i).getStudentNo() + ""); //党校号
                    cell = row.createCell(7, Cell.CELL_TYPE_STRING);
                    cell.setCellValue(students.get(i).getExamScore() + ""); //初试成绩
                    cell = row.createCell(8, Cell.CELL_TYPE_STRING);
                    cell.setCellValue(students.get(i).getMakeUpScore() + ""); //补考成绩
                }
                response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding("utf-8");
                String fileName = URLEncoder.encode("学生成绩.xls", "utf-8");
                response.setHeader("Content-disposition", "attachment;filename="
                        + fileName);//附件下载，不同浏览器是否选择路径不同效果，火狐会选路径
                OutputStream os = response.getOutputStream();
                workbook.write(os);
                os.flush();
                os.close();
                return new JSONResult(0, "下载成功");
            } else {
                return new JSONResult(0, "没有内容可以下载");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new JSONResult(1, "下载失败");
        }
    }

    @RequestMapping("/deleteAll")
    @ResponseBody
    public JSONResult deleteAll() {
        try {
            studentService.deleteAll();
            return new JSONResult(0, "已清空所有考生");
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(1, "清空出现错误");
        }
    }

}
